package com.fayuan.nocv.TXApi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fayuan.nocv.entity.NocvData;
import com.fayuan.nocv.entity.NocvNews;
import com.fayuan.nocv.service.IndexService;
import com.fayuan.nocv.service.NocvNewsService;
import com.fayuan.nocv.vo.BarVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Component
@Slf4j
public class BaiduHot {

    @Autowired
    private IndexService indexService;

    @Autowired
    private NocvNewsService nocvNewsService;
    @Scheduled(fixedDelay = 3600000)
    public void BaiduHotSave() {
        HttpUtils3 httpUtils3 = new HttpUtils3();
        try {
            String s = httpUtils3.getData();
            JSONObject jsonObject = JSONObject.parseObject(s);
            JSONArray data = jsonObject.getJSONArray("data");
            List<NocvNews>nocvNewsList = new ArrayList<>();
            for (Object datum : data) {
                JSONObject jsonObject1 = JSONObject.parseObject(datum.toString());
                NocvNews nocvNews = new NocvNews();
                Object title = jsonObject1.get("word");
                Object pic = jsonObject1.get("img");
                Object desc = jsonObject1.get("desc");

                nocvNews.setTitle(title.toString());
                nocvNews.setContent(desc.toString());
                nocvNews.setPic(pic.toString());
                nocvNews.setCreateTime(new Date());
                nocvNewsList.add(nocvNews);
            }
            QueryWrapper<NocvNews>wrapper = new QueryWrapper<>();
            nocvNewsService.remove(wrapper);
            boolean b = nocvNewsService.saveBatch(nocvNewsList);
            if (b){
                log.info("百度新闻数据插入成功！");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
